<?php
/**
 * Created by JetBrains PhpStorm.
 * User: caixudong
 * Date: 11-12-13
 * Time: 下午5:26
 */

class CRUD extends Model{
    private $table;
    public $select_db = 'admin';

    static public function getInstance($table){
        static $instances = array();

        if (! isset($instances[$table]))
        {
            $instances[$table] = new self();
            $instances[$table]->table = $table;
        }
        return $instances[$table];
    }

    public function update($where,$params = array()){
        if(!$where || !$params){
            return false;
        }

        $sets = array();
        foreach($params as $k=>$v){
            $sets[] = ' '.$k.'=:'.$k;
        }

        $set = implode(',',$sets);

        $sql = "update $this->table set $set where $where";

        return $this->db()->execute($sql,$params);

    }

    public function insert($params = array()){
        if(!$params){
            return false;
        }

        $filed_arr       = array();
        $filed_value_arr = array();
        foreach($params as $k=>$v){
            $filed_arr[]   = $k;
            $filed_value_arr[] = ':' . $k;
        }

        $fileds       = implode(',', $filed_arr);
        $filed_values = implode(',', $filed_value_arr);
        $sql          = "insert into {$this->table}($fileds) values($filed_values)";
        $this->db()->execute($sql,$params);
        return $this->db()->lastInsertId();
    }

    public function delete($where,$params){
        if(!$where || !$params){
            return false;
        }

        $sql          = "delete from {$this->table} where $where";
        return $this->db()->execute($sql,$params);
    }
}